# Contributor: Wang Qi <ericwq057@qq.com>
# Maintainer: Wang Qi <ericwq057@qq.com>
pkgname=aprilsh
pkgver=0.7.12
pkgrel=0
pkgdesc="Remote shell support intermittent or mobile network"
url="https://github.com/ericwq/aprilsh"
arch="all"
license="MIT"
depends="$pkgname-client=$pkgver-r$pkgrel $pkgname-server=$pkgver-r$pkgrel"
makedepends="go protoc utmps-dev ncurses ncurses-terminfo musl-locales protoc-gen-go"
subpackages="
	$pkgname-client
	$pkgname-server
	$pkgname-openrc
	$pkgname-doc
	"
source="$pkgname-$pkgver.tar.gz::https://github.com/ericwq/aprilsh/archive/refs/tags/$pkgver.tar.gz
	apshd.logrotate
	apshd.initd"

_build_tag="-tags utmps"

export GOCACHE="${GOCACHE:-"$srcdir/go-cache"}"
export GOTMPDIR="${GOTMPDIR:-"$srcdir"}"
export GOMODCACHE="${GOMODCACHE:-"$srcdir/go"}"

prepare() {
	default_prepare

	protoc --go_out=. -I . ./protobufs/transportInstruction.proto
	protoc --go_out=. -I . ./protobufs/hostInput.proto
	protoc --go_out=. -I . ./protobufs/userInput.proto
}

build() {
	_module_name=$(head ./go.mod | grep '^module' | awk '{print $2}')
	_go_version=$(go version | grep 'version' | awk '{print $3}')

	_date_str=$(date -u "+%Y-%m-%dT%H:%M:%SZ" ${SOURCE_DATE_EPOCH:+-d @$SOURCE_DATE_EPOCH})
	local ldflags="-s -w \
		-X $_module_name/frontend.BuildTime=$_date_str \
		-X $_module_name/frontend.GitBranch=HEAD \
		-X $_module_name/frontend.GitCommit=cb93a1a \
		-X $_module_name/frontend.GitTag=$pkgver \
		-X $_module_name/frontend.GoVersion=$_go_version \
		"
	go build $_build_tag -ldflags="$ldflags" -o ./bin/apshd ./frontend/server
	go build -ldflags="$ldflags" -o ./bin/apsh ./frontend/client
}

check() {
	# shellcheck disable=2046
	APRILSH_APSHD_PATH="$builddir/bin/apshd" \
		go test $_build_tag $(go list ./... | grep -Ev '(data|protobufs)')
}

package() {
	install -Dm755 ./bin/apshd ./bin/apsh -t "$pkgdir/usr/bin"
	install -Dm644 ./doc/*.md -t "$pkgdir/usr/share/doc/$pkgname/"
	install -Dm755 "$srcdir"/apshd.initd "$pkgdir"/etc/init.d/apshd
	install -Dm644 "$srcdir"/apshd.logrotate "$pkgdir"/etc/logrotate.d/apshd
}

client() {
	pkgdesc="$pkgname client"
	depends="musl-locales ncurses ncurses-terminfo"
	amove usr/bin/apsh
}

server() {
	pkgdesc="$pkgname server"
	depends="musl-locales utmps ncurses ncurses-terminfo openssh-server"
	amove usr/bin/apshd
}

sha512sums="
e23df17cf3e88b6bce2d0d9c2ea365605fb493534a0fbf578ac2c1e3d9e0c82fdacc3b0e02d8f864f10dd9173a361bf8679faa1cac9ef5a8d37e1f9cd93867a8  aprilsh-0.7.12.tar.gz
5e65b2c344d31928398234eacf08e153d2edf991709703ffa4905abffac516658be8146bab5cd4cd31d8812619e9c85aac344537546d15ca57a3e2dc83051f48  apshd.logrotate
f7afd2a135c2d3c6357f02ed4e580e85275de2fcd2d1c3dabefffeca4fecb4cc8f21243e97440b17256cb56a8c006b81635d418ab5457b5b4aa78deac5d00dd1  apshd.initd
"
